<template>
  <div class="pending-questions">
    <el-card shadow="hover" class="pending-card">
      <template #header>
        <div class="card-header">
          <span>待审核问题</span>
          <el-button type="primary" size="small" @click="getPendingQuestions">
            <el-icon><Refresh /></el-icon>刷新
          </el-button>
        </div>
      </template>
      
      <!-- 待审核问题列表 -->
      <el-table
        v-loading="loading"
        :data="pendingQuestions"
        style="width: 100%"
        border
        @selection-change="handlePendingSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="userName" label="提问者" width="120" />
        <el-table-column prop="createTime" label="提交时间" width="180" />
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              plain
              @click="navigateToDetail(scope.row.id)"
            >查看</el-button>
            <el-button
              type="success"
              size="small"
              plain
              @click="reviewQuestion(scope.row.id, 1)"
            >通过</el-button>
            <el-button
              type="danger"
              size="small"
              plain
              @click="showRejectDialog(scope.row.id)"
            >拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 批量操作 -->
      <QuestionBatchActions
        v-if="selectedPending.length > 0"
        :count="selectedPending.length"
        @batch-approve="batchApprovePending"
        @batch-reject="showBatchRejectDialog"
      />
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 拒绝问题对话框 -->
    <el-dialog
      title="拒绝问题"
      v-model="rejectDialogVisible"
      width="40%"
    >
      <el-form :model="rejectForm" label-width="80px">
        <el-form-item label="拒绝理由" required>
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRejectQuestion">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue';
import { 
  getPendingQuestions as apiGetPendingQuestions,
  reviewQuestion as apiReviewQuestion
} from '../../api/admin';
import QuestionBatchActions from './QuestionBatchActions.vue';

const props = defineProps({});
const emit = defineEmits(['refresh']);
const router = useRouter();

// 待审核问题相关
const pendingQuestions = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedPending = ref([]);
const loading = ref(false);

// 拒绝问题对话框
const rejectDialogVisible = ref(false);
const rejectForm = ref({
  questionId: null,
  reason: ''
});

// 获取待审核问题列表
const getPendingQuestions = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value
    };
    
    const response = await apiGetPendingQuestions(params);
    if (response.code === 200) {
      pendingQuestions.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取待审核问题列表失败');
    }
  } catch (error) {
    console.error('获取待审核问题列表失败:', error);
    ElMessage.error('获取待审核问题列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理待审核问题选择变化
const handlePendingSelectionChange = (selection) => {
  selectedPending.value = selection;
};

// 处理待审核问题分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getPendingQuestions();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getPendingQuestions();
};

// 显示拒绝问题对话框
const showRejectDialog = (questionId) => {
  rejectForm.value.questionId = questionId;
  rejectForm.value.reason = '';
  rejectDialogVisible.value = true;
};

// 确认拒绝问题
const confirmRejectQuestion = async () => {
  if (!rejectForm.value.reason) {
    ElMessage.warning('请输入拒绝理由');
    return;
  }
  
  try {
    const response = await apiReviewQuestion(
      rejectForm.value.questionId,
      4,
      rejectForm.value.reason
    );
    
    if (response.code === 200) {
      ElMessage.success('问题已拒绝');
      rejectDialogVisible.value = false;
      getPendingQuestions();
    } else {
      ElMessage.error(response.message || '拒绝问题失败');
    }
  } catch (error) {
    console.error('拒绝问题失败:', error);
    ElMessage.error('拒绝问题失败');
  }
};

// 显示批量拒绝对话框
const showBatchRejectDialog = () => {
  if (selectedPending.value.length === 0) {
    ElMessage.warning('请选择要拒绝的问题');
    return;
  }
  
  rejectForm.value.questionId = null; // 批量拒绝时使用selectedPending
  rejectForm.value.reason = '';
  rejectDialogVisible.value = true;
};

// 审核问题
const reviewQuestion = async (id, status) => {
  if (status === 4) {
    showRejectDialog(id);
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确定要通过此问题吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await apiReviewQuestion(id, status);
    if (response.code === 200) {
      ElMessage.success('问题审核通过');
      getPendingQuestions();
    } else {
      ElMessage.error(response.message || '问题审核失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('问题审核失败:', error);
      ElMessage.error('操作失败');
    }
  }
};

// 批量通过待审核问题
const batchApprovePending = async () => {
  if (selectedPending.value.length === 0) {
    ElMessage.warning('请选择要通过的问题');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确定要通过选中的${selectedPending.value.length}个问题吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const promises = selectedPending.value.map(question => apiReviewQuestion(question.id, 1));
    await Promise.all(promises);
    
    ElMessage.success(`已通过${selectedPending.value.length}个问题`);
    getPendingQuestions();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量通过问题失败:', error);
      ElMessage.error('操作失败');
    }
  }
};

// 导航到详情页
const navigateToDetail = (id) => {
  router.push(`/question/${id}`);
};

// 初始化
onMounted(() => {
  getPendingQuestions();
});

// 暴露方法给父组件
defineExpose({
  getPendingQuestions
});
</script>

<style scoped>
.pending-questions {
  width: 100%;
}

.pending-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}
</style> 